package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("uploadController")
public class UploadController {

@RequestMapping("/upload")
@ResponseBody
    public void Upload(MultipartFile[] files, HttpServletRequest request) throws IOException {
        for (MultipartFile multipartFile : files) {
            if(!multipartFile.isEmpty()){
                //1 获取上传的目录
                String path = request.getServletContext().getRealPath("/upload");
                //2 生成唯一的文件名
                //2.1 获取到原始文件名
                String filename = multipartFile.getOriginalFilename();
                //2.2 生成唯一UUID
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");

                //2.3 获取文件的后缀名
                String suffix = filename.substring(filename.lastIndexOf("."));
                //2.4 组合成新的文件名
                filename=uuid+suffix;
                //3 保存到硬盘目录
                multipartFile.transferTo(new File(path,filename));

            }
        }
    }
}
